package transport.netty.server;

import entity.RpcRequest;
import entity.RpcResponse;
import enumeration.ResponseStatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import provider.ServiceProvider;
import provider.ServiceProviderImpl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//处理响应 返回请求
public class RequestHandler {
    private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
    public static final ServiceProvider serviceProvider;

    static {
        serviceProvider = new ServiceProviderImpl();
    }

    public Object handle(RpcRequest rpcRequest) {
        Object service = serviceProvider.getService(rpcRequest.getInterfaceName());
        return invokeTargetMethod(rpcRequest, service);
    }

    //反射 根据方法名调用对象
    public Object invokeTargetMethod(RpcRequest rpcRequest, Object service) {
        Object result = null;
        try {
            //反射考虑重载 方法名+参数类型
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
            result = method.invoke(service, rpcRequest.getParameterObjects());
            logger.info("服务{},成功调用方法{}", rpcRequest.getInterfaceName(), rpcRequest.getMethodName());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            return RpcResponse.failure(ResponseStatusCode.SERVICE_NOT_FOUND, rpcRequest.getRequestId());
        }
        return result;
    }

}
/*
 * 根据方法名 反射调用
 * 未知对象类型
 * */